home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 6056 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: solon.com!not-for-mail
  2. From: wgb@netcom.com (Bill Bosacker)
  3. Newsgroups: comp.lang.c.moderated,comp.lang.c
  4. Subject: Re: Please help me elect rounding of int division
  5. Date: 22 Feb 1996 06:42:19 -0600
  6. Organization: WGB Enterprises
  7. Sender: clc@solutions.solon.com
  8. Approved: clc@solutions.solon.com
  9. Message-ID: <4ghobb$dpp@solutions.solon.com>
  10. References: <4gfaif$1tt@solutions.solon.com> <4ggbm9$85t@solutions.solon.com>
  11. NNTP-Posting-Host: solutions.solon.com
  12. X-Newsreader: Forte Agent .99d/32.182
  13.  
  14. Gihan Perera <Gihan@andante.demon.co.uk> wrote:
  15.  
  16. :In article <4gfaif$1tt@solutions.solon.com>
  17. :           swedecj@vcnet.com "Carl Jacobson" writes:
  18. :
  19. :> Please help me solve this task.
  20. :> 
  21. :> I have now tried (Borland C++ version 3.0) for two solid days to write
  22. :> a function that would allow me to round the quotient of (a/b) up or
  23. :> down based on the "nearest" integer instead of being truncated to the
  24. :> smallest. If exactly half way, return the "odd."
  25. :
  26. :The first part is easy.  If you're using reals, add 0.5 to (a/b) before
  27. :truncating it.  If you're doing the whole thing with integers, use:
  28. :
  29. :   q = ( a + b/2 ) / b;
  30. :
  31. :which has the same effect.
  32. :
  33. :But neither of these meets your second criterion ("return the odd") -
  34. :they both round _up_ if exactly half-way.  Sorry - I don't know any
  35. :easy trick for that.
  36.  
  37. Try this:
  38.  
  39. x = (a + b/2) / b;
  40. y = x  - ((2 * (a % b) == b) && (!x & 1));
  41.  
  42. The expression (2 * (a % b) == b) detects a remainder of exactly 0.5b
  43. and (!x & 1) returns 1 if x is even, thus assuring that y is odd.
  44.  
  45. Later......
  46. ----------------------------------------------------------------------------
  47. WGB Enterprises                                                Bill Bosacker
  48. P.O. Box 9267                                                 wgb@netcom.com
  49. Whittier, CA 90608-9267                              A TAG is a TAG is a TAG
  50.